define(function() {
    'use strict';

    function ctrl($scope,$timeout,$stateParams,$state,$ionicPopup,$ionicLoading,$ionicHistory,$ionicModal,$rootScope,$sce,
                  $q,LocalCacheService,CommonService,InfoService,DictionaryService,WebService) {

        var par = $scope.param = {};

        $scope.$on('$ionicView.beforeEnter', function() {
            par.prodCode = $stateParams['prodCode'];
            par.prodSource = $stateParams['prodSource'];
            par.add = $stateParams['add'];

            init();
        });

        function init(){
            par.isSuccess = false; // 是否显示结果页
            par.continueBuyUrl = '';

            $scope.buy = {}; //页面值
            $scope.buy.checkProtocol = true;
            $scope.buy.checkRisk = true;
            $scope.buy.checkOpen = true ;
            $scope.pay = {};
            $scope.pay.payAccountStatus = -1;
            $scope.buy.risk_confirm_flag = false;
            $scope.payWays = [];
            $scope.depositBankData = new Array(); //三方存管银信息
            $scope.quickBankData = {}; //快捷支付银行
            $scope.cmsProdInfo = {};
            $scope.ifsProdInfo = {};
            $scope.buy2 = {};

            createModel().then(afterCreateModel);

            WebService.getUserInfo().then(
                function(user){

                    $scope.user = user;
                    initEvent();
                }, function(){
                    LocalCacheService.removeUser();
                    $rootScope.$emit("userIntercepted","sessionOut");
                }
            );
        }

        function createModel(){
            var deferred = $q.defer();
            if(!$scope.buy2Modal) {
                $ionicModal.fromTemplateUrl("trade/buyStep2.html", {
                    scope: $scope,
                    animation: "slide-in-up"
                }).then(function(modal) {
                    $scope.buy2Modal = modal;
                    deferred.resolve();
                });
            } else {
                deferred.resolve();
            }
            return deferred.promise;
        }

        function afterCreateModel(){
            var pay = LocalCacheService.get("SelectPayWayCtrl_pay");
            var buy = LocalCacheService.get("BuyCtrl_buy");
            var forwardView = $ionicHistory.forwardView();
            if(buy) {
                $scope.buy = buy;
            }
            if(forwardView && (forwardView.stateName == "selectPayWay" || forwardView.stateName == "recharge-and-withdraw")) {
                queryPayInfo(pay);
            }
        }

        function initEvent(){
            //理财体验活动新增 可以直接买基金
            if(CommonService.isBuyExperience()) {
                par.continueBuyUrl = "#" + LocalCacheService.get("lcty_state").url;
            } else {
                par.continueBuyUrl = "#/tab/product-index";
            }
            //产品代码或产品类型为空，提示
            if(CommonService.isStrEmpty(par.prodCode) || CommonService.isStrEmpty(par.prodSource)){
                var alertPopup = CommonService.showConfig({title: "提示", message : "未选择任何产品"});
                $timeout(function() {
                    alertPopup.close();
                    $state.go("tab.product-index");
                }, 3000);
            }
            //查询用户使用已绑定存管银行
            WebService.getUserDepositBankCards().then(
                function (data) {
                    $scope.depositBankData = data;
                    queryQuickBank();
                },function (){
                    queryQuickBank();
                }
            );


            if($scope.user.corp_risk_status != null && $scope.user.corp_risk_status != "0"){
                var corp_risk_content;
                if($scope.user.corp_risk_status == "1"){
                    corp_risk_content = "您还未进行风险测评，请先完成风险测评，才能购买此产品！";
                }else if($scope.user.corp_risk_status =="2"){
                    corp_risk_content = "您的风险测评结果已过期，请重新完成风险测评，才能购买此产品！";
                }
                $scope.riskConfirmPopup = $ionicPopup.confirm({
                    cssClass: "kDialog",
                    template: corp_risk_content,
                    cancelText : "放弃",
                    okText: '去风险测评'
                });
                $scope.riskConfirmPopup.then(function(res) {
                    if(res) {
                        var currentView = $ionicHistory.currentView();
                        $state.go("tab.account-risk",{from:currentView.stateName, fromParams: angular.toJson(currentView.stateParams),step:1});
                    } else {
                        $ionicHistory.goBack();
                    }
                });

            }

        }

        function queryQuickBank(){
            WebService.getUserQuickBankCards().then(
                function (data){
                    $scope.quickBankData = data;
                    var depositBankData = $scope.depositBankData;
                    if("0,2".indexOf(par.prodSource) > -1){
                        if(depositBankData.length == 0){
                            noDepositBank();
                        }else if("1,3".indexOf(depositBankData[0].bkaccount_regflag) > -1){
                            depositBankOnWay(depositBankData[0].bkaccount_regflag);
                        }else{
                            queryProductInfo(par.prodCode, par.prodSource, queryIFSProdInfo);
                        }
                    }else{
                        if((depositBankData.length == 0 || "1,3".indexOf(depositBankData[0].bkaccount_regflag) > -1)
                            && $scope.quickBankData.length == 0 ){
                            noBankInfo();
                        }else{
                            queryProductInfo(par.prodCode, par.prodSource, queryIFSProdInfo);
                        }
                    }
                },function (){
                    noBankInfo();
                }
            )
        }

        var queryProductInfo = function (prodCode,prodSource, func){
            InfoService.getFundGeneral(prodCode).then(function (data){
                if(data){
                    $scope.cmsProdInfo = data;
                    //显示产品名称及收益数据
                    if("0,1,2,3".indexOf($scope.cmsProdInfo.prod_profit_mode) < 0){
                        CommonService.showConfig({message:"产品收益模式未配置:"+$scope.cmsProdInfo.prod_code});
                    }
                    //特殊产品，获取协议列表
                    func(prodCode,prodSource, queryEncontract);
                }else{
                    $ionicLoading.hide();
                    CommonService.showAlert({message:"未获取到产品信息"});
                }
            });
        };

        var queryIFSProdInfo =function (prodCode,prodSource, func){
            WebService.queryIFSProdInfo(prodCode,prodSource).then(
                function (ifsProdMsg){
                    if(ifsProdMsg.length == 1){
                        $scope.ifsProdInfo = ifsProdMsg[0];
                        //最低申购金额
                        $scope.buy.entrust_balance_placeholder = getPlaceholderString($scope.cmsProdInfo, par.add);
                        func();
                    }else{
                        $ionicLoading.hide();
                        CommonService.showAlert({message:"基金信息查询失败"});
                    }
                }
            );
        };

        var isTAOpen = function (){
            var prodta_no = "";
            if(par.prodSource=='0'||par.prodSource=='1'){
                prodta_no = $scope.ifsProdInfo.prodta_no;
            }else if(par.prodSource=='2'){
                prodta_no = $scope.ifsProdInfo.fund_company;
            }
            //查询TA是否已开户
            WebService.isTAOpen(par.prodSource,prodta_no).then(
                function (data) {
                    par.ta_open=data.ta_open;
                }
            );
        }


        var queryEncontract = function (){
            InfoService.getProdFiles($scope.cmsProdInfo.prod_id).then(function(data){
                if(data && data.length > 0){
                    $scope.agreementList = data;
                }
                isTAOpen();
            });
            $ionicLoading.hide();
        };

        $scope.entrustBalanceBlur = function (){
            var entrust_balance = parseFloat($scope.buy.entrust_balance);
            if(isNaN(entrust_balance) && $scope.cmsProdInfo && $scope.cmsProdInfo.prod_code){
                $scope.buy.entrust_balance_placeholder = getPlaceholderString($scope.cmsProdInfo, par.add);
            }
        };

        $scope.next = function (){
            if(checkSetp1()){
                queryPayInfo();
            }
        };


        var checkSetp1 = function(){
            if(!$scope.buy.checkProtocol && $scope.agreementList){//选中
                CommonService.showAlert({message:"请勾选我已阅读并同意《"+$scope.cmsProdInfo.prod_name+"购买协议》"});
                return false;
            }

            if(!par.isOpen&&!$scope.buy.checkOpen){//选中
                CommonService.showAlert({message:"请勾选同意开通该机构TA账户"});
                return false;
            }

            $scope.buy.risk_confirm_flag = false ;
            if((parseFloat($scope.user.corp_risk_level)<parseFloat($scope.cmsProdInfo.prod_risk_level))){
                if(!$scope.buy.checkRisk){
                    CommonService.showAlert({message:"请勾选同意购买的基金风险等级高于风险承受等级"});
                    return false;
                }else{
                    $scope.buy.risk_confirm_flag = true ;
                }
            }

            if(isNaN(parseFloat($scope.buy.entrust_balance))){
                CommonService.showAlert({message:"请正确输入购买金额！"});
                return false;
            }
            if (!CommonService.checkRegex("^[0-9]+(.[0-9]{1,2})?$",$scope.buy.entrust_balance)) {
                $scope.buy.entrust_balance = parseFloat($scope.buy.entrust_balance.toFixed(2));
            }
            var entrust_balance= $scope.buy.entrust_balance;
            if(entrust_balance==0){
                CommonService.showAlert({message:"输入金额必须大于零"});
                return false;
            }
            var ifsProdInfo = $scope.ifsProdInfo;
            if(ifsProdInfo){
                if(par.add=="1"){
                    if(entrust_balance < parseFloat($scope.cmsProdInfo.prod_status == "4" ?
                            $scope.cmsProdInfo.allot_limitshare : $scope.cmsProdInfo.prod_allot_subscribe)){
                        CommonService.showAlert({message:"输入金额应大于或等于最低追加金额"});
                        return false;
                    }
                }else{
                    if(entrust_balance <  parseFloat($scope.cmsProdInfo.prod_status == "4" ?
                            $scope.cmsProdInfo.prod_min_share : $scope.cmsProdInfo.prod_min_subscribe)){
                        CommonService.showAlert({message:"输入金额应大于或等于最低购买金额"});
                        return false;
                    }
                }
                if($scope.cmsProdInfo.prod_catalog_mark == 'otcfdsy' &&entrust_balance%10000!=0){
                    CommonService.showAlert({message:"输入金额须为10000元的整数倍"});
                    return false;
                }
            }
            return true;
        };

        function queryPayInfo(pay){
            if(pay) {
                $scope.pay = pay;
                showConfirm();
            } else {
                WebService.checkPayStatus($scope.buy.entrust_balance).then(
                    function (data){
                        $scope.pay.payAccountStatus = data.status;
                        if(data.status == -1){
                            CommonService.showAlert({message:"查询支付方式失败,请检查保证金账户和快捷支付是否正常"});
                            return;
                        } else if(data.status == 1){//保证金足
                            $scope.pay.html = '<span class="txt">保证金账户余额支付</span>';
                            $scope.pay.pay_kind=0;
                            $scope.pay.bank_no=0;
                            $scope.pay.pay_account="";
                            $scope.pay.full=true; //保证金足
                        }else if(data.status == 4){//未开保证金和银行卡
                            noBankInfo();
                            return;
                        } else {
                            if(par.prodSource=='1'){
                                if(data.status == 2){//保证金不足
                                    if(data.card){//如果用户绑定了快捷支付卡，选中快捷支付卡
                                        var bankAccount = data.card.bank_account;
                                        $scope.pay.html= '<span class="title">快捷支付</span><span class="txt_m">' + data.card.bank_name + ' 尾号' + bankAccount.substring(bankAccount.length-3) + '</span>';
                                        $scope.pay.pay_kind=1;
                                        $scope.pay.bank_no=data.card.bank_no;
                                        $scope.pay.pay_account=bankAccount;
                                    }else{//无快捷支付卡 提示充值
                                        $scope.pay.html = '<span class="txt"><em>余额不足，请充值</em>保证金账户余额支付</span>';
                                        $scope.pay.pay_kind=0;
                                        $scope.pay.bank_no=0;
                                        $scope.pay.pay_account="";
                                    }
                                }else if(data.status == 3){//快捷支付
                                    var bankAccount = data.card.bank_account;
                                    $scope.pay.html= '<span class="title">快捷支付</span><span class="txt_m">' + data.card.bank_name + ' 尾号' + bankAccount.substring(bankAccount.length-3) + '</span>';
                                    $scope.pay.pay_kind=1;
                                    $scope.pay.bank_no=data.card.bank_no;
                                    $scope.pay.pay_account=bankAccount;
                                }
                            }else if(par.prodSource=='0' || par.prodSource=='2'){
                                if(data.status == 2 || data.status == 3){//保证金不足
                                    $scope.pay.html = '<span class="txt"><em>余额不足，请充值</em>保证金账户余额支付</span>';
                                    $scope.pay.pay_kind=0;
                                    $scope.pay.bank_no=0;
                                    $scope.pay.pay_account="";
                                }
                            }
                        }
                        showConfirm();
                    }
                );
            }
        }

        $scope.closeModal = function() {
            $scope.buy2Modal.hide();
        };

        $scope.$on('$destroy', function() {
            $scope.buy2Modal.remove();
        });

        function showConfirm(){
            $scope.buy2.password = null;
            LocalCacheService.set("BuyCtrl_buy", $scope.buy); //保存购买的金额
            $scope.buy2Modal.show();
        }

        //选择其他支付方式
        $scope.selectOtherPayWay = function() {
            if(par.prodSource=='2' && ($scope.pay.payAccountStatus=='1' || $scope.pay.payAccountStatus=='3')){
                return false;
            }
            LocalCacheService.set("BuyCtrl_pay", $scope.pay);
            LocalCacheService.set("BuyCtrl_quickBankData", $scope.quickBankData);
            $scope.buy2Modal.hide();
            $state.go("selectPayWay");
        };

        $scope.goRecharge = function() {
            LocalCacheService.set("BuyCtrl_pay", $scope.pay);
            LocalCacheService.set("BuyCtrl_quickBankData", $scope.quickBankData);
            $scope.buy2Modal.hide();
            $state.go("recharge-and-withdraw");
        };

        var noDepositBank = function(){
            $ionicPopup.show({
                cssClass: "kDialog",
                template: '<p>抱歉，该产品需绑定三方存管银行才可购买。您需要再绑定一张三方存管银行卡。</p>'+
                        '<a href="#/help?key=help/bank/bank_introduce" class="fs0 clr1">为什么要绑定三方存管银行卡？</a>',
                title: '未绑定存管银行',
                buttons: [
                    { text: '取消',
                        onTap: function(e) {
                            $ionicHistory.goBack();
                    }},
                    { text: '<b>立即绑定</b>',
                        type: 'button-positive',
                        onTap: function(e) {
                            $state.go("tab.account-bindDepositBank");
                        }
                    }
                ]
            });
        };

        var depositBankOnWay = function(regflag){
            var title = "绑定存管银行未确认";
            var str = '抱歉，您的三方存取已在受理中，请等待确认后再购买。';
            if("1" == regflag){
                title = "绑定存管银行未激活";
                str = '抱歉，您的三方存取尚未激活，请激活后再购买。';
            }
            $ionicPopup.show({
                cssClass: "kDialog",
                template: '<div class="panel"><div class="item">'+str+'	</div></div>',
                title: title,
                buttons: [
                    { text: '确定',
                        onTap: function(e) {
                            $ionicHistory.goBack();
                        }}
                ]
            });
        };

        var noBankInfo = function(){
            $ionicLoading.hide();
            $ionicPopup.show({
                cssClass: "kDialog",
                template: '您还未绑定任何银行卡，请绑定银行卡后再进行购买。',
                title: '提示',
                buttons: [
                    { text: '取消',
                        onTap: function(e) {
                            $ionicHistory.goBack();
                        }},
                    { text: '<b>立即绑定</b>',
                        type: 'button-positive',
                        onTap: function(e) {
                            $state.go("tab.account-bank");
                        }
                    }
                ]
            });
        };

        function checkStep2(){
            if($scope.pay.pay_kind == 0 && !$scope.pay.full){
                if(par.prodSource=='0' || par.prodSource=='2') {
                    CommonService.showAlert({message:"保证金余额不足，请充值"});
                } else {
                    CommonService.showAlert({message:"保证金余额不足，请充值或选择其他支付方式"});
                }
                return false;
            }
            var password = $scope.buy2.password;
            if(CommonService.isStrEmpty(password)){
                CommonService.showAlert({message:"请输入交易密码"});
                return false;
            }
            return true;
        }

        $scope.submitBuy = function(){
            if(checkStep2()){
                $ionicLoading.show("正在提交购买请求");
                var buyPromise = null;
                if(par.prodSource=='0'){
                    buyPromise = WebService.buyBankProduct($scope.ifsProdInfo.prod_code, $scope.buy2.password, $scope.buy.entrust_balance, $scope.pay.pay_kind,
                        $scope.pay.bank_no, $scope.pay.pay_account, $scope.ifsProdInfo.prodta_no, $scope.cmsProdInfo.prod_name, $scope.cmsProdInfo.prod_setup_date,
                        $scope.buy.risk_confirm_flag);
                }else if(par.prodSource=='1'){
                    buyPromise = WebService.buyDjProduct($scope.ifsProdInfo.prod_code, $scope.buy2.password, $scope.buy.entrust_balance, $scope.pay.pay_kind,
                        $scope.pay.bank_no, $scope.pay.pay_account, $scope.ifsProdInfo.prodta_no, $scope.cmsProdInfo.prod_name, $scope.cmsProdInfo.prod_setup_date,
                        $scope.buy.risk_confirm_flag);
                }else if(par.prodSource=='2'){
                    buyPromise = WebService.buyUfProduct($scope.ifsProdInfo.fund_code, $scope.ifsProdInfo.fund_company, $scope.buy2.password, $scope.buy.entrust_balance,
                        $scope.ifsProdInfo.charge_type, $scope.cmsProdInfo.prod_name, $scope.cmsProdInfo.prod_setup_date, $scope.buy.risk_confirm_flag);
                }
                buyPromise.then(
                    function (data){
                        $ionicLoading.hide();
                        buySuccess(data);
                    }, function (result){
                        $ionicLoading.hide();
                        if("XCM-300001" == result.error_no) {//显示通知
                            CommonService.showNotice(result.error_info);
                        }else if("XCM-100001" == result.error_no || result.error_no.indexOf("160073") > -1){
                            CommonService.showAlert({message:result.error_info});
                        }else{
                            CommonService.showConfig({message:result.error_info});
                        }
                    }
                );
            }
        };

        function buySuccess(data){
            $scope.buy2Modal.hide();
            LocalCacheService.remove("SelectPayWayCtrl_pay");
            if(CommonService.isBuyExperience()) {//理财体验活动
                location.href = localStorage["redirect_url"];
            }
            //显示收益时间
            par.isSuccess = true;
            $scope.success = data;
            var start_date = data.profit_start_date;
            var show_date = data.profit_show_date;
            var begin_date = $scope.cmsProdInfo.prod_setup_date;
            //起始收益日 显示收益日
            if(!CommonService.isStrEmpty(start_date) && !CommonService.isStrEmpty(show_date)){
                $scope.success.type = 1;
                var profitStartDate = new Date(start_date.substr(0,4),parseFloat(start_date.substr(4,2))-1,start_date.substr(6,2));
                $scope.success.income_begin_time = new XDate(profitStartDate).toString("MM-dd") + " " + weeks[profitStartDate.getDay()];
                var profitShowDate = new Date(show_date.substr(0,4),parseFloat(show_date.substr(4,2))-1,show_date.substr(6,2));
                $scope.success.income_show_time = new XDate(profitShowDate).toString("MM-dd") + " " + weeks[profitShowDate.getDay()];
                //产品成立日
            }else{
                $scope.success.type = 2;
                $scope.success.begin_time = $sce.trustAsHtml('产品成立当日确认购买份额，开始计算收益');
                if(!CommonService.isStrEmpty(begin_date) && begin_date.length >=8){
                    var prodBeginDate = new Date(begin_date.substr(0,4),parseFloat(begin_date.substr(4,2))-1,begin_date.substr(6,2));
                    $scope.success.begin_time = new XDate(prodBeginDate).toString("MM-dd") + " " + weeks[prodBeginDate.getDay()];
                }
            }
            //查询渠道是否有问卷
            if($scope.cmsProdInfo.prod_catalog_mark=='otcfdsy'){
                WebService.getChannelPaper(par.prodCode, $scope.buy.entrust_balance).then(function (data){
                    if(data && data.paper_id && data.remaining_number > 0){
                        showChannelRisk(data.paper_id, par.prodCode);
                    }
                },function (result){});
            }
        }

        //渠道问卷
        function showChannelRisk(paper_id, prodCode){
            $ionicPopup.confirm({
                cssClass: "kDialog",
                template: "您已完成购买，请关注“天风证券小财迷”微信公众号，填写体验问卷，参与抽奖活动，即有机会赢取1000元现金大奖！",
                buttons: [{ text: '我知道了'}]
            });
        }

        function placeholder(share){
            var str = share ? (share == 0 ? "购买金额需≥0.01元" : "购买金额需≥"+ share + "元") : "";
            return str;
        }


        function getPlaceholderString(prodInfo, isAdd){
            var placeholderString = "";
            if(prodInfo) {
                if(isAdd=="1"){
                    if(prodInfo.prod_status == "4"){
                        placeholderString = placeholder(prodInfo.prod_allot_share);//追加认购最低
                    }else{
                        placeholderString = placeholder(prodInfo.prod_allot_subscribe);//追加申购最低
                    }
                }else{
                    if($scope.cmsProdInfo.prod_status == "4"){
                        placeholderString = placeholder(prodInfo.prod_min_share);//认购最低
                    }else{
                        placeholderString = placeholder(prodInfo.prod_min_subscribe);//申购最低
                    }
                }
            }
            return placeholderString;
        }


        var weeks = DictionaryService.getWeeks();
    }

    ctrl.$inject = ['$scope','$timeout','$stateParams','$state','$ionicPopup','$ionicLoading','$ionicHistory','$ionicModal','$rootScope','$sce',
        '$q','LocalCacheService','CommonService','InfoService','DictionaryService','WebService'];
    return ctrl;
});
